// @Author EthanScriptOn
// @Desc
package foreground

import (
	"fmt"
	"gitee.com/fatzeng/srf_switch_basic_components/util"
	"gitee.com/fatzeng/srf_switch_client_demo/common"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director"
	directorcommon "gitee.com/fatzeng/srf_switch_dynamic_logic_director/common"
	directorconfig "gitee.com/fatzeng/srf_switch_dynamic_logic_director/config"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/pojo"
	"gitee.com/fatzeng/srf_switch_stream_bridge/bridge"
)

var AdaptationExecutorMappingRelationship = make(map[bridge.Group]*common.ExecutionElement)

func DirectorStart() error {
	common.Initialization()
	cacheAdaptationConfig()
	directorconfig.SrfSwitchEventPublisherFunction = util.GenerateOnceInitializer(func() (result interface{}, err error) {
		return func(log *pojo.SrfSwitchPublishLog) error {
			if log == nil {
				return fmt.Errorf("log is nil")
			}
			env := log.Env
			namespace := log.Namespace
			group := log.Group
			config := bridge.Group{Env: env, NameSpace: namespace, Group: group}
			element, ok := AdaptationExecutorMappingRelationship[config]
			if !ok {
				return fmt.Errorf("can not find executor mapping")
			}
			return element.Executor.Execute(element.Ctx)
		}, nil
	})
	directorconfig.MysqlEngine = util.GenerateOnceInitializer(func() (result interface{}, err error) {
		return nil, nil
	})
	return srf_switch_dynamic_logic_director.DirectorStart()
}

func cacheAdaptationConfig() {
	for _, resourceConfig := range directorcommon.SrfDirectorGlobalConfig.SrfResourceConfig {
		env := resourceConfig.SrfEnvConfig.SrfEnv
		namespace := resourceConfig.SrfLocatorConfig.SrfNamespace
		group := resourceConfig.SrfLocatorConfig.SrfGroup
		bridgeGroup := bridge.Group{Env: env, NameSpace: namespace, Group: group}
		element, ok := common.ExecutorMappingRelationship[common.PRODUCER][bridgeGroup]
		if !ok {
			continue
		}
		bridgeConfigs := make([]*bridge.BridgeConfig, 0)
		for _, bridgeConfig := range resourceConfig.SrfBridgeConfig {
			if bridgeConfig.SrfDsUniqueness == "" {
				continue
			}
			response, hasResponse := element.Ctx.GetAdaptationBridgeConfig(bridgeConfig.SrfDsUniqueness)
			if !hasResponse {
				continue
			}
			bridgeConfigs = append(bridgeConfigs, response...)
		}
		if len(bridgeConfigs) <= 0 {
			continue
		}
		clone := element.Ctx.ShallowClone()
		clone.SetGroupConfig(&bridge.GroupConfig{
			Group:         &bridgeGroup,
			BridgeConfigs: bridgeConfigs,
		})
		AdaptationExecutorMappingRelationship[bridgeGroup] = &common.ExecutionElement{
			Executor: element.Executor,
			Ctx:      clone,
		}
	}
}
